// import { login, logout, getInfo } from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth' // removeToken
import { againUser } from '@/api/user.js'
// import { resetRouter } from '@/router'
// 导入登录api
import { login } from '@/api/login'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {},
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  setToken (state, payload) {
    state.token = payload
    // console.log(state.token)
    setToken(payload)
  },
  setUserInfo (state, userInfo) {
    state.userInfo = { ...userInfo } // 用 浅拷贝的方式去赋值对象 因为这样数据更新之后，才会触发组件的更新
  },
  // 删除用户信息
  reomveUserInfo (state) {
    state.userInfo = {}
  },

  // 删除缓存
  removeToken (state) {
    state.token = null // 删除vuex的token
    removeToken() // 先清除 vuex  再清除缓存 vuex和 缓存数据的同步
  }
}

const actions = {
  async login (context, payload) {
    const res = await login(payload)
    context.commit('setToken', res.data.data.jwt)
    context.commit('setUserInfo', res.data.data.user)
  },
  async getUse (context, payload) {
    const res = await againUser()
    context.commit('setUserInfo', res.data.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
